package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.handler.codec.http.HttpHeaders;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;

@Component
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter {
    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private JwtTool jwtTool;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和response
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        //2. 获取请求路径
        String path = request.getURI().getPath();
        boolean bo = authProperties.getExcludePaths().stream().anyMatch(url->antPathMatcher.match(url, path));
        //3.判断路径是否需要对令牌进行校验，如果不需要直接放行
        if(bo){
            return chain.filter(exchange);
        }
        //4.需要校验拦截，获取请求头中的令牌
        String token = request.getHeaders().getFirst("Authorization");
        //5.校验令牌
        Long userId = null;
        try {
            userId=jwtTool.parseToken(token);
        } catch (Exception e) {
        //6.校验不通过，执行拦截操作
            response.setStatusCode(HttpStatus.UNAUTHORIZED); //响应状态码
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON); //响应JSON类型
            return response.writeWith(Mono.just(response.bufferFactory().wrap("{\"msg\":\"请先登录！\"}".getBytes(StandardCharsets.UTF_8))));
        }
        //7.解析令牌，获取用户信息把ID放到请求头里
        String userInfo = userId.toString();
        request.mutate().headers(httpHeaders -> httpHeaders.set("userInfo", userInfo));



        //8.放行
        return chain.filter(exchange);
    }
}
